//
//  HMEmoticonKeyboardView.swift
//  表情键盘
//
//  Created by iOS on 16/9/26.
//  Copyright © 2016年 iOS. All rights reserved.
//

import UIKit

// oc需要 objc/runtime.h

/// 整个表情键盘的view
class HMEmoticonKeyboardView: UIView {
    
    /// 键盘对应的textView
    weak var textView: UITextView?

    @IBOutlet weak var bottomView: HMEmoticonBottomView!
    
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var layout: UICollectionViewFlowLayout!
    
    @IBOutlet weak var pageControl: UIPageControl!
    class func emoticonKeyboardView() -> HMEmoticonKeyboardView {
        return Bundle.main.loadNibNamed("HMEmoticonKeyboardView", owner: nil, options: nil)?.last as! HMEmoticonKeyboardView
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        // 5.设置底部按钮的代理
        bottomView.delegate = self
        
        // 设置collectionView
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.register(HMEmoticonPageCell.self, forCellWithReuseIdentifier: "cell")
        
        // 设置pageControl的样式
        // _pageImage
        // _currentPageImage
        pageControl.setValue(UIImage(named: "compose_keyboard_dot_normal"), forKey: "_pageImage")
        pageControl.setValue(UIImage(named: "compose_keyboard_dot_selected"), forKey: "_currentPageImage")
        pageControl.isHidden = true
    }
    
    override func layoutSubviews() {
        // layoutSubView后子控件的frame就有值了
        super.layoutSubviews()
        
        layout.itemSize = collectionView.bounds.size
    }
}

// 6.遵守协议
extension HMEmoticonKeyboardView: HMEmoticonBottomViewDelegate {
    // 7.实现协议里面的方法
    func didSelected(type: HMEmoticonBottomViewType) {
        print("点击了 \(type.rawValue)")
        
        // 让collectionView滚动到对应的组
        let indexPath = IndexPath(item: 0, section: type.rawValue)
        collectionView.scrollToItem(at: indexPath, at: .left, animated: false)
        
        // 设置pageControl的数量
        setupPageControl(indexPath: indexPath)
    }
}

extension HMEmoticonKeyboardView: UICollectionViewDataSource, UICollectionViewDelegate {
    // 设置collectionView的组数
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return HMEmoticonManager.shared.packages.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return HMEmoticonManager.shared.packages[section].pageEmoticons.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! HMEmoticonPageCell
        
        cell.indexPath = indexPath
//        cell.backgroundColor = UIColor.random
        // 找到对应那组的表情包
        let package = HMEmoticonManager.shared.packages[indexPath.section]
        // 找到对应那一页的表情模型
        let pageEmoticon = package.pageEmoticons[indexPath.item]
        cell.pageEmoticon = pageEmoticon
        
        // 5.成为代理
        cell.delegate = self
        
        return cell
    }
    
    /// 当collectionView一滚动就做事情
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        // 参照点,哪个cell的frame包含这个参照点就表示那个cell占用屏幕的位置多一点,就选中这个组
        var refPoint = scrollView.center
        refPoint.x += scrollView.contentOffset.x
//        print("refPoint = \(refPoint)")
        
        // 获取到正在显示的cell
        for cell in collectionView.visibleCells {
//            print("cell.frame = \(cell.frame)")
            // frame是否包含某个点
            if cell.frame.contains(refPoint) {
                // 通过cell获取对应的indexPath
                let indexPath = collectionView.indexPath(for: cell)!
//                print("找到这个cell: \(indexPath)")
                // 让indexPath这个组对应的按钮选中
                bottomView.selectSection(section: indexPath.section)
                
                // 设置pageControl的数量
                setupPageControl(indexPath: indexPath)
                
                break
            }
        }
    }
    
    func setupPageControl(indexPath: IndexPath) -> Void {
        pageControl.numberOfPages = HMEmoticonManager.shared.packages[indexPath.section].pageEmoticons.count
        pageControl.currentPage = indexPath.item
        
        // 第0组隐藏pageControl,其他组显示
        pageControl.isHidden = indexPath.section == 0
    }
}

// 6.遵守协议
extension HMEmoticonKeyboardView: HMEmoticonPageCellDelegate {
    func emoticonPageCellDidClickDeleteButton() {
//        print("删除按钮被点击了")
        textView?.deleteBackward()
    }
    
    /// 表情按钮被点击了
    func emoticonPageCellDidClickEmoticonButton(emoticonModel model: HMEmoticonModel) {
        // 将表情添加到textView上面
        textView?.insertEmoticon(emoitcon: model)
        
        // 当点击的是最近这组不需要再添加到最近这组里面
        let indexPath = collectionView.indexPathsForVisibleItems.first
        if indexPath?.section == 0 {
            // 显示的是最近这组
            return
        }
        
        // 将表情添加到最近这组里面
        HMEmoticonManager.shared.addRecentEmoticon(emoticon: model)
        // 刷新collectionView的第0组
        var indexSet = IndexSet()
        indexSet.insert(0)
//        indexSet.insert(1)
//        indexSet.insert(2)
        collectionView.reloadSections(indexSet)
    }
    
    
//    /// 添加一个表情到TextView中
//    ///
//    /// - parameter emoitcon: 表情模型
//    func insertEmoticon(emoitcon: HMEmoticonModel) {
//        guard let textView = self.textView else {
//            print("textView 没有值")
//            return
//        }
//        
//        // emoji表情
//        if let emoji = emoitcon.emoji {
//            // 将emoji(文本)添加到textView中
//            textView.insertText(emoji)
//            return
//        }
//        
//        // 图片表情
//        if let fullPngPath = emoitcon.fullPngPath {
//            // 1.生成图片
//            let image = UIImage(named: fullPngPath)
//            
//            // 图片是不能直接添加到textView文本中的.和发邮件一样可以使用附件(属性文本)
//            // 2.将图片转成附件
//            let attachment = HMTextAttachment()
//            attachment.image = image
//            attachment.chs = emoitcon.chs
//            let height = textView.font?.lineHeight ?? 0
//            // 设置附件大小
//            // frame 往下移动 设置y 为正数
//            // bounds 和 frame相反 往下移动 设置y 为负数
//            attachment.bounds = CGRect(x: 0, y: -3, width: height, height: height)
//            
//            // 3.将附件转成属性文本
//            let attributeText = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
//            // 3.0.1 给附件添加font属性
//            attributeText.addAttribute(NSFontAttributeName, value: textView.font!, range: NSRange(location: 0, length: 1))
//            
//            
//            // 3.1获取当前textView中的属性文本
//            let currentAttributeText = NSMutableAttributedString(attributedString: textView.attributedText)
//            // 3.2获取当前选中的范围
//            let currentSelectedRange = textView.selectedRange
//            // 3.3当图片的属性文本添加到现有的属性文本中
//            currentAttributeText.replaceCharacters(in: currentSelectedRange, with: attributeText)
//            
//            // 4.让textView显示属性文本
//            textView.attributedText = currentAttributeText
//            // 5.重新设置光标位置
//            let newSelectedRange = NSRange(location: currentSelectedRange.location + 1, length: 0)
//            textView.selectedRange = newSelectedRange
//        }
//    }
}
